package tdt4240.iddqd.database;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.content.ContentValues;
import android.content.Context;

public class DatabaseAdapter {

	private DatabaseHelper db;

	public DatabaseAdapter(Context con){
		db = new DatabaseHelper(con);
	}

	/**
	 * Load player progress from database as a value pair (level_id,checkpoint_id)
	 * Falls back to (1,0) if no previous value exists
	 * @return The value pair in a int-array of length two
	 */
	public int[] load(){
		SQLiteDatabase dbR = db.getReadableDatabase();
		Cursor cursor = dbR.query(DatabaseHelper.TABLE_NAME, new String[]{ DatabaseHelper.LEVEL_ID, DatabaseHelper.CHECKPOINT_ID }, null, null, null, null, null);

		int[] r;

		if(cursor.getCount() > 0) {
			cursor.moveToFirst();
			r = new int[]{ cursor.getInt(0), cursor.getInt(1) };
		}
		else {
			r = new int[]{ 1, 0 };
		}

		dbR.close();
		return r;
	}

	/**
	 * Save player progress in database in columns (level_id,checkpoint_id)
	 * @param levelId Level ID
	 * @param checkpointId Checkpoint ID
	 */
	public void save(int levelId, int checkpointId) {
		SQLiteDatabase dbW = db.getWritableDatabase();
		dbW.delete(DatabaseHelper.TABLE_NAME, null, null);

		ContentValues values = new ContentValues();
		values.put(DatabaseHelper.LEVEL_ID, levelId);
		values.put(DatabaseHelper.CHECKPOINT_ID, checkpointId);
		dbW.insert(DatabaseHelper.TABLE_NAME, null, values);
		dbW.close();

	}

	public void closeDatabase(){
		db.close();
	}

}
